/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package slsBeans;

import EL.FoodTypes;
import EL.Foods;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Tian
 */
@Stateless
public class FoodBLO implements FoodBLORemote
{

    @PersistenceContext(unitName = "Tunga_EJB3PU")
    private EntityManager em;

    public List<Foods> getAll()
    {
        String hql = "From Foods";
        Query query = this.em.createQuery(hql);
        List<Foods> foods = query.getResultList();
        return foods;
    }

    public Foods getByID(int id)
    {
        Foods food = this.em.find(Foods.class, id);
        return food;
    }

    public Foods getByName(String name)
    {

        return null;
    }

    public boolean add(Foods food, FoodTypes foodType)
    {
        try
        {
            List<Foods> foods = new ArrayList<Foods>();
            foods.add(food);

            food.setFoodTypes(foodType);
            foodType.setFoodsList(foods);
            this.em.persist(food);
            return true;
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            return false;
        }
    }

    public boolean edit(Foods food)
    {
        try
        {
            this.em.merge(food);
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean delete(int id)
    {
        Foods food = getByID(id);
        if (food != null)
        {
            try
            {
                this.em.remove(food);
                return true;
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
                return false;
            }
        }
        return false;
    }

    public List<Foods> getFoodByFoodType(String foodType)
    {
        String hql = "FROM Foods as f WHERE f.foodTypes.category=?1";
        Query query = this.em.createQuery(hql);
        query.setParameter(1, foodType);
        List<Foods> foods = query.getResultList();
        return foods;
    }

    public List<Foods> getByCategory(String category)
    {
        return null;
    }

}
